# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'interface.ui'
#
# Created: Mon Mar 17 22:03:44 2014
#      by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
#
# Authors: Bruno Alves, n.º 6152; Neuza Figueira, n.º 6036

from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTableWidgetItem, QMessageBox
import signal
from PyQt4 import *
import sys

from PortScan import Port_Scan
import IPSubnetCalc

from ConnectionSearch import Connection_Search

from FirewallData import Firewall_Data

from functools import partial

import psutil

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Interface(QtGui.QMainWindow):
    '''Autogenerated class by PyQt4.''' 
    def setupUi(self, MainWindow):
        '''Autogenerated method to create the interface elements.
           @param MainWindow -> QMainWindow object.'''
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(430, 340)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.tabWidget = QtGui.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 461, 401))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Arial"))
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.tabWidget.setFont(font)
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
        self.tab = QtGui.QWidget()
        self.tab.setObjectName(_fromUtf8("tab"))
        self.pushButton = QtGui.QPushButton(self.tab)
        self.pushButton.setGeometry(QtCore.QRect(140, 10, 161, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.label = QtGui.QLabel(self.tab)
        self.label.setGeometry(QtCore.QRect(20, 70, 61, 16))
        self.label.setObjectName(_fromUtf8("label"))
        self.lineEdit = QtGui.QLineEdit(self.tab)
        self.lineEdit.setGeometry(QtCore.QRect(80, 70, 113, 20))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.label_2 = QtGui.QLabel(self.tab)
        self.label_2.setGeometry(QtCore.QRect(20, 120, 46, 13))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.listView = QtGui.QListWidget(self.tab)
        self.listView.setGeometry(QtCore.QRect(80, 120, 111, 101))
        self.listView.setObjectName(_fromUtf8("listView"))
        self.label_3 = QtGui.QLabel(self.tab)
        self.label_3.setGeometry(QtCore.QRect(250, 70, 46, 13))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.listView_2 = QtGui.QListWidget(self.tab)
        self.listView_2.setGeometry(QtCore.QRect(250, 90, 151, 131))
        self.listView_2.setObjectName(_fromUtf8("listView_2"))
        self.label_4 = QtGui.QLabel(self.tab)
        self.label_4.setGeometry(QtCore.QRect(10, 260, 81, 16))
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.pushButton_2 = QtGui.QPushButton(self.tab)
        self.pushButton_2.setGeometry(QtCore.QRect(90, 260, 75, 23))
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.pushButton_3 = QtGui.QPushButton(self.tab)
        self.pushButton_3.setGeometry(QtCore.QRect(200, 260, 75, 23))
        self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
        self.pushButton_4 = QtGui.QPushButton(self.tab)
        self.pushButton_4.setGeometry(QtCore.QRect(310, 260, 75, 23))
        self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
        self.tabWidget.addTab(self.tab, _fromUtf8(""))
        self.tab_2 = QtGui.QWidget()
        self.tab_2.setObjectName(_fromUtf8("tab_2"))
        self.pushButton_5 = QtGui.QPushButton(self.tab_2)
        self.pushButton_5.setGeometry(QtCore.QRect(140, 10, 171, 31))
        self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
        self.label_5 = QtGui.QLabel(self.tab_2)
        self.label_5.setGeometry(QtCore.QRect(20, 70, 71, 16))
        self.label_5.setObjectName(_fromUtf8("label_5"))
        self.listView_3 = QtGui.QListWidget(self.tab_2)
        self.listView_3.setGeometry(QtCore.QRect(20, 90, 151, 161))
        self.listView_3.setObjectName(_fromUtf8("listView_3"))
        self.label_6 = QtGui.QLabel(self.tab_2)
        self.label_6.setGeometry(QtCore.QRect(190, 70, 91, 16))
        self.label_6.setObjectName(_fromUtf8("label_6"))
        self.listView_4 = QtGui.QListWidget(self.tab_2)
        self.listView_4.setGeometry(QtCore.QRect(190, 90, 211, 161))
        self.listView_4.setObjectName(_fromUtf8("listView_4"))
        self.label_7 = QtGui.QLabel(self.tab_2)
        self.label_7.setGeometry(QtCore.QRect(20, 270, 71, 16))
        self.label_7.setObjectName(_fromUtf8("label_7"))
        self.pushButton_6 = QtGui.QPushButton(self.tab_2)
        self.pushButton_6.setGeometry(QtCore.QRect(100, 270, 75, 23))
        self.pushButton_6.setObjectName(_fromUtf8("pushButton_6"))
        self.pushButton_7 = QtGui.QPushButton(self.tab_2)
        self.pushButton_7.setGeometry(QtCore.QRect(200, 270, 75, 23))
        self.pushButton_7.setObjectName(_fromUtf8("pushButton_7"))
        self.pushButton_8 = QtGui.QPushButton(self.tab_2)
        self.pushButton_8.setGeometry(QtCore.QRect(300, 270, 75, 23))
        self.pushButton_8.setObjectName(_fromUtf8("pushButton_8"))
        self.tabWidget.addTab(self.tab_2, _fromUtf8(""))
        self.tab_3 = QtGui.QWidget()
        self.tab_3.setObjectName(_fromUtf8("tab_3"))
        self.pushButton_9 = QtGui.QPushButton(self.tab_3)
        self.pushButton_9.setGeometry(QtCore.QRect(140, 10, 131, 31))
        self.pushButton_9.setObjectName(_fromUtf8("pushButton_9"))
        self.columnView = QtGui.QTableWidget(self.tab_3)
        self.columnView.setGeometry(QtCore.QRect(20, 50, 381, 141))
        self.columnView.setObjectName(_fromUtf8("columnView"))
        self.label_8 = QtGui.QLabel(self.tab_3)
        self.label_8.setGeometry(QtCore.QRect(20, 210, 71, 16))
        self.label_8.setObjectName(_fromUtf8("label_8"))
        self.pushButton_10 = QtGui.QPushButton(self.tab_3)
        self.pushButton_10.setGeometry(QtCore.QRect(90, 210, 91, 23))
        self.pushButton_10.setObjectName(_fromUtf8("pushButton_10"))
        self.pushButton_11 = QtGui.QPushButton(self.tab_3)
        self.pushButton_11.setGeometry(QtCore.QRect(200, 210, 91, 23))
        self.pushButton_11.setObjectName(_fromUtf8("pushButton_11"))
        self.label_9 = QtGui.QLabel(self.tab_3)
        self.label_9.setGeometry(QtCore.QRect(20, 260, 61, 16))
        self.label_9.setObjectName(_fromUtf8("label_9"))
        self.pushButton_12 = QtGui.QPushButton(self.tab_3)
        self.pushButton_12.setGeometry(QtCore.QRect(110, 260, 75, 23))
        self.pushButton_12.setObjectName(_fromUtf8("pushButton_12"))
        self.pushButton_13 = QtGui.QPushButton(self.tab_3)
        self.pushButton_13.setGeometry(QtCore.QRect(210, 260, 75, 23))
        self.pushButton_13.setObjectName(_fromUtf8("pushButton_13"))
        self.pushButton_14 = QtGui.QPushButton(self.tab_3)
        self.pushButton_14.setGeometry(QtCore.QRect(310, 260, 75, 23))
        self.pushButton_14.setObjectName(_fromUtf8("pushButton_14"))
        self.tabWidget.addTab(self.tab_3, _fromUtf8(""))
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.listView, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem *)")), self.selItem1)
        QtCore.QObject.connect(self.listView_3, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem *)")), self.selItem2)

        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.scan_current_network)
        QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8("clicked()")), self.scan_active_connections)
        QtCore.QObject.connect(self.pushButton_9, QtCore.SIGNAL(_fromUtf8("clicked()")), self.scan_firewall_data)

        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        '''Autogenerated method by PyQt4.
           @param MainWindow -> QMainWindow object.'''
        MainWindow.setWindowTitle(_translate("MainWindow", "GUI", None))
        self.pushButton.setText(_translate("MainWindow", "Scan Current Network", None))
        self.label.setText(_translate("MainWindow", "Network:", None))
        self.label_2.setText(_translate("MainWindow", "Hosts:", None))
        self.label_3.setText(_translate("MainWindow", "Ports:", None))
        self.label_4.setText(_translate("MainWindow", "Export to:", None))
        self.pushButton_2.setText(_translate("MainWindow", "CSV", None))
        self.pushButton_3.setText(_translate("MainWindow", "Database", None))
        self.pushButton_4.setText(_translate("MainWindow", "PDF", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Port Scan", None))
        self.pushButton_5.setText(_translate("MainWindow", "Scan Active Connections", None))
        self.label_5.setText(_translate("MainWindow", "Processes:", None))
        self.label_6.setText(_translate("MainWindow", "Connections:", None))
        self.label_7.setText(_translate("MainWindow", "Export to:", None))
        self.pushButton_6.setText(_translate("MainWindow", "CSV", None))
        self.pushButton_7.setText(_translate("MainWindow", "Database", None))
        self.pushButton_8.setText(_translate("MainWindow", "PDF", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Connection Scan", None))
        self.pushButton_9.setText(_translate("MainWindow", "Scan Firewall Log", None))
        self.label_8.setText(_translate("MainWindow", "Graphics:", None))
        self.pushButton_10.setText(_translate("MainWindow", "World Map", None))
        self.pushButton_11.setText(_translate("MainWindow", "Statistics", None))
        self.label_9.setText(_translate("MainWindow", "Export to:", None))
        self.pushButton_12.setText(_translate("MainWindow", "CSV", None))
        self.pushButton_13.setText(_translate("MainWindow", "Database", None))
        self.pushButton_14.setText(_translate("MainWindow", "PDF", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Firewall Scan", None))


    def selItem1(self, item):
        '''Method to populate the host and port list on the interface.
           @param item -> selected host from the list.'''
        self.listView_2.clear()

        cur = str(item.text())
        scan = Port_Scan()
        print 'Scanning...'
        ports = scan.scan_host(cur)
        print 'Finished!'

        for port, state in ports:
            item2 = QListWidgetItem('Port ' + str(port) + ': ' + state)
            self.listView_2.addItem(item2)

        self.pushButton_2.clicked.connect(partial (self.csv_portscan, item, ports))
        self.pushButton_3.clicked.connect(partial (self.database_portscan, item, ports))
        self.pushButton_4.clicked.connect(partial (self.pdf_portscan, item, ports))


    def scan_current_network(self):
        '''Method for the click event of the button which scans the current network.'''
        self.listView.clear()
        self.lineEdit.clear()

        scan = Port_Scan()
        ip = scan.get_ip_address('eth0')
        mask = scan.get_network_mask('eth0')
        network = IPSubnetCalc.ip_subnet_calc(ip, mask)
        self.lineEdit.setText(network)
        print 'Scanning...'
        #hosts_list = scan.portscan(network)
        hosts_list = scan.portscan('10.0.2.15')
        print 'Finished!'

        for host, status in hosts_list:
            item = QListWidgetItem(host)
            self.listView.addItem(item)


    def csv_portscan(self, item, ports):
        '''Method for the click event of the button which creates the csv files for the port scan results.
           @param item -> Selected host from the list.
           @param ports -> Opened ports from host.'''
        scan = Port_Scan()
        scan.create_csv_files(item.text(), ports)


    def database_portscan(self, item, ports):
        '''Method for the click event of the button which creates the database for the port scan results.
           @param item -> Selected host from the list.
           @param ports -> Opened ports from host.'''
        scan = Port_Scan()
        scan.create_database(item.text(), ports)


    def pdf_portscan(self, item, ports):
        '''Method for the click event of the button which creates the pdf files for the port scan results.
           @param item -> Selected host from the list.
           @param ports -> Opened ports from host.'''
        scan = Port_Scan()
        scan.create_pdf(item.text(), ports)


    def selItem2(self, item):
        '''Method to populate the processes and active connections on the interface.
           @param item -> Selected process from the list.'''
        self.listView_4.clear()

        a = item.text().split("#")

        scan = Connection_Search()
        print 'Scanning...'
        connections = scan.get_active_connections(int(a[0]))
        print 'Finished!'

        connections = connections.replace("[", "")
        connections = connections.replace("]", "")
        test = []

        if connections == "No Active Connections!":
            myList = connections
            item2 = QListWidgetItem(myList)
            self.listView_4.addItem(item2)
            pass
        else:
            myList = connections.split("connection")
            myList = [i for i in myList if i != '']

            for i in range(len(myList)):
                if (myList[i]).endswith(", "):
                    myList[i] = myList[i][:-2]
                
                item2 = QListWidgetItem(str(i + 1) + ": " + myList[i][1:-1])
                self.listView_4.addItem(item2)


        self.pushButton_6.clicked.connect(partial (self.csv_connection_scan, item, myList))
        self.pushButton_7.clicked.connect(partial (self.database_connection_scan, item, myList))
        self.pushButton_8.clicked.connect(partial (self.pdf_connection_scan, item, myList))

    
    def scan_active_connections(self):
        '''Method for the click event of the button which scans the running processes.'''
        self.listView_3.clear()

        scan = Connection_Search()
        print 'Scanning...'
        processes = scan.get_active_processes()
        print 'Finished!'
        
        for process in processes:
            item = QListWidgetItem(str(process) + "# " + psutil.Process(int(process)).name)
            self.listView_3.addItem(item)


    def csv_connection_scan(self, item, connections):
        '''Method for the click event of the button which creates the csv files for the active connections results.
           @param item -> Selected process from the list.
           @param connections -> Active connections of the selected process.'''
        scan = Connection_Search()
        scan.create_csv_files(item.text(), connections)


    def database_connection_scan(self, item, connections):
        '''Method for the click event of the button which creates the database for the active connections results.
           @param item -> Selected process from the list.
           @param connections -> Active connections of the selected process.'''
        scan = Connection_Search()
        scan.create_database(item.text(), connections)


    def pdf_connection_scan(self, item, connections):
        '''Method for the click event of the button which creates the pdf files for the active connections results.
           @param item -> Selected process from the list.
           @param connections -> Active connections of the selected process.'''
        scan = Connection_Search()
        scan.create_pdf(item.text(), connections)


    def scan_firewall_data(self):
        '''Method for the click event of the button which scans the firewall log.'''
        self.columnView.clear()
        scan = Firewall_Data()
        info, ip_list = scan.read_firewall_log()

        self.columnView.setRowCount(len(info))
        self.columnView.setColumnCount(len(info[0]))
       
        self.columnView.setHorizontalHeaderLabels(['IP', 'Date', 'Time', 'Location'])
        
        data = []
        print 'Reading...'

        for i in range(len(info)):
            for j in range(len(info[0])):
                if info[i][j] == None:
                    info[i][j] = 'Not detected'

                item = QTableWidgetItem(info[i][j])
                item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.columnView.setItem(i,j ,item)
                data.append(scan.geo_ip_lookup(info[i][0]))

        self.columnView.resizeColumnsToContents()

        print 'Finished!'

        self.pushButton_10.clicked.connect(partial (self.world_map_firewall_data, data))
        self.pushButton_11.clicked.connect(partial (self.statistics_firewall_data, ip_list))
        self.pushButton_12.clicked.connect(partial (self.csv_firewall_data, info))
        self.pushButton_13.clicked.connect(partial (self.database_firewall_data, info))
        self.pushButton_14.clicked.connect(partial (self.pdf_firewall_data, info))


    def world_map_firewall_data(self, data):
        '''Method for the click event of the button which creates a world map showing the attack source.
           @param data -> Data from the firewall log regarding geographic coordinates of the IP's.'''
        scan = Firewall_Data()
        scan.build_world_map(data)


    def statistics_firewall_data(self, ip_list):
        ''''Method for the click event of the button which creates graphical statistics regarding number of attacks by IP.
           @param data -> Data from the firewall log regarding number of attacks.'''
        scan = Firewall_Data()
        scan.build_bars_graph(ip_list)


    def csv_firewall_data(self, info):
        '''Method for the click event of the button which creates the csv files for the firewall log scan results.
           @param info -> Data from the firewall log regarding date, time and location of the attacks.'''
        scan = Firewall_Data()
        scan.create_csv_files(info)


    def database_firewall_data(self, info):
        '''Method for the click event of the button which creates the database for the firewall log scan results.
           @param info -> Data from the firewall log regarding date, time and location of the attacks.'''
        scan = Firewall_Data()
        scan.create_database(info)


    def pdf_firewall_data(self, info):
        '''Method for the click event of the button which creates the csv files for the firewall log scan results.
           @param info -> Data from the firewall log regarding date, time and location of the attacks.'''
        scan = Firewall_Data()
        scan.create_pdf(info)


    def login(self):
        '''Method to show the modal dialog with the login interface.'''
        loginDialog = Login_Dialog()

        if loginDialog.exec_():
            self.show()
        else:
            loginDialog.exec_()


class Login_Dialog(QtGui.QDialog):
    '''Class to create the modal dialog for the login.'''
    def __init__(self, parent=None):
        '''Method to initialize the dialog and it's components.
           @reference: http://stackoverflow.com/questions/9689053/how-to-communicate-or-switch-between-two-windows-in-pyqt4'''
        super(Login_Dialog, self).__init__(parent)

        self.username = QtGui.QLineEdit()
        self.password = QtGui.QLineEdit()
        self.password.setEchoMode(QtGui.QLineEdit.Password)
        loginLayout = QtGui.QFormLayout()
        loginLayout.addRow("Username", self.username)
        loginLayout.addRow("Password", self.password)

        self.buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok)
        self.buttons.accepted.connect(self.check)
        self.buttons.rejected.connect(self.reject)

        layout = QtGui.QVBoxLayout()
        layout.addLayout(loginLayout)
        layout.addWidget(self.buttons)
        self.setLayout(layout)


    def check(self):
        '''Method to check the login credentials.'''
        if str(self.username.text()) == "user" and str(self.password.text()) == "debian": # do actual login check
            self.accept()
            self.close()
        else:
            msgBox = QMessageBox() 
            msgBox.setText("Wrong username or password!")
            msgBox.exec_()


    def reject(self):
        '''Method to close the dialog.'''
        sys.exit()

def main():
    '''Main method.'''
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Interface()
    ui.setupUi(MainWindow)
    ui.login()
    MainWindow.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
